// 优化后的云函数代码
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

exports.main = async (event) => {
  const db = cloud.database()
  const MAX_LIMIT = 100

  // 参数校验
  if (!event.adcode) {
    return {
      code: 400,
      message: '缺少必要参数：adcode'
    }
  }

  try {
    // 获取记录总数
    const countResult = await db.collection('Pois')
      .where({ adcode: event.adcode })
      .count()

    const total = countResult.total
    if (total === 0) {
      return {
        code: 200,
        data: [],
        message: '无相关数据'
      }
    }

    // 分批次获取（移除field过滤）
    const batchTimes = Math.ceil(total / MAX_LIMIT)
    const tasks = []
    for (let i = 0; i < batchTimes; i++) {
      const promise = db.collection('Pois')
        .where({ adcode: event.adcode })
        .skip(i * MAX_LIMIT)
        .limit(MAX_LIMIT)
        .get() // 移除field过滤
      tasks.push(promise)
    }

    // 合并数据
    const res = (await Promise.all(tasks)).reduce((acc, cur) => ({
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg
    }))

    const processedData = res.data.map(item => ({
      ...item,
      location: item.location ?
        `${item.location.longitude},${item.location.latitude}` : ''
    }))

    // 保持原始数据结构（移除location格式转换）
    return {
      code: 200,
      data: processedData, // 直接返回原始数据
      message: `查询到${res.data.length}条记录`
    }
  } catch (err) {
    console.error('数据库查询失败:', err)
    return {
      code: 500,
      message: '数据库查询失败',
      error: err
    }
  }
}